//
//  WNBaseVC.swift
//  WalkNovel
//
//  Created by Kevin on 2023/7/4.
//

import UIKit
import Reachability
import SnapKit
import HandyJSON
import RxSwift
import RxCocoa
import MJRefresh

class WNBaseVC: UIViewController {
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    lazy var navView: WNNavView = {
        let view = WNNavView.init(frame: CGRect(x: 0, y: 0, width: ScreenW, height: NaviTotalHeight))
        view.isHidden = false
        view.leftClosure = {[weak self] in
            self?.navigationController?.popViewController(animated: true)
        }
        view.rightClosure = {[weak self] in }
        return view
    }()
    
    lazy var bgBtn: UIButton = {
        let btn = UIButton(type: .custom)
        btn.backgroundColor = .init(white: 0, alpha: 0.55)
        btn.rx.tap.bind { [weak self] in
            if ((self?.pickerVC) != nil) {
                self?.showPickVC(completion: { _ in })
            }
            if ((self?.rateVC) != nil) {
                self?.showRateVC(completion: { _ in })
            }
            if ((self?.giftVC) != nil) {
                self?.showGiftVC(completion: { _ in })
            }
        }.disposed(by: rx.disposeBag)
        btn.isHidden = true
        return btn
    }()
    
    let reachability = try? Reachability()
    
    var isFirst = true
    
    var baseId = ""
    
    var page: Int = 1

    var hasPage: Bool = false
        
    var modalSource = 0
        
    var pageName = ""

    var pickerVC: WNPickerVC!
    
    var rateVC: WNRateVC!
    
    var giftVC: WNGiftVC!
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        reachability?.stopNotifier()
        WNBuriedManager.shared.leavePage(pageName)

    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        try? reachability?.startNotifier()
        WNBuriedManager.shared.enterPage(pageName)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.clipsToBounds = true
        view.backgroundColor = .white
        view.addSubview(navView)
        view.addSubview(bgBtn)
        bgBtn.snp.makeConstraints { (make) in
            make.top.left.bottom.right.equalTo(0)
        }
        viewConfig()
        dataConfig()
        handleNoti()
    }
    
    func viewConfig() {
        
    }
    
    func dataConfig() {

    }
    
    func handleNoti() {
        
    }
    
    func wn_hidNavView() {
        navView.isHidden = true
    }
    
    // 关闭暗黑模式
    override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
        super.traitCollectionDidChange(previousTraitCollection)
        if traitCollection.verticalSizeClass != previousTraitCollection?.verticalSizeClass || traitCollection.horizontalSizeClass != previousTraitCollection?.horizontalSizeClass {
            if #available(iOS 13.0, *) {
                overrideUserInterfaceStyle = .light
            }else {
                // Fallback on earlier versions
            }
        }
    }
}

extension WNBaseVC {
    
    func getUserGold(_ completion: @escaping (Int) -> Void) {
        WNPayManager.shared.getBalance { balance in
            completion(WNSingleData.shared.userGold)
        }
    }
}

extension WNBaseVC {
    /// Picker选择器
    func showPickVC(_ show: Bool = false, _ pickerType: PickerType = .none, _ components: Int = 0, _ currentStr: String = "", completion: @escaping (String) -> Void) {
        var h = TabBarMargin+225
        if pickerType == .sex {
            h = TabBarMargin+194
        }
        if pickerVC == nil {
            pickerVC = WNPickerVC(pickerType, components, currentStr)
            pickerVC.view.frame = CGRect(x: 0, y: ScreenH, width: ScreenW, height: h)
            pickerVC.finshClosure = { [weak self] str in
                self?.showPickVC(completion: { _ in })
                if str != "取消" {
                    completion(str)
                }
            }
            addChild(pickerVC)
            view.addSubview(pickerVC.view)
            view.bringSubviewToFront(bgBtn)
            view.bringSubviewToFront(pickerVC.view)
        }
        bgBtn.isHidden = !show
        UIView.animate(withDuration: 0.25, delay: 0, options: [.curveLinear, .allowUserInteraction], animations: {
            self.pickerVC.view.transform = CGAffineTransform(translationX: 0, y: show ? -h : 0)
        }) { (finish) in
            if finish {
                if !show {
                    self.pickerVC.view.removeFromSuperview()
                    self.pickerVC.removeFromParent()
                    self.pickerVC = nil
                }
            }
        }
    }
    
    /// Rate选择器
    func showRateVC(_ show: Bool = false, completion: @escaping (String) -> Void) {
        let h = TabBarMargin+380
        if rateVC == nil {
            rateVC = WNRateVC()
            rateVC.view.frame = CGRect(x: 0, y: ScreenH, width: ScreenW, height: h)
            rateVC.finshClosure = { [weak self] str in
                self?.showRateVC(completion: { _ in })
                if str != "取消" {
                    completion(str)
                }
            }
            addChild(rateVC)
            view.addSubview(rateVC.view)
            view.bringSubviewToFront(bgBtn)
            view.bringSubviewToFront(rateVC.view)
        }
        bgBtn.isHidden = !show
        UIView.animate(withDuration: 0.25, delay: 0, options: [.curveLinear, .allowUserInteraction], animations: {
            self.rateVC.view.transform = CGAffineTransform(translationX: 0, y: show ? -h : 0)
        }) { (finish) in
            if finish {
                if !show {
                    self.rateVC.view.removeFromSuperview()
                    self.rateVC.removeFromParent()
                    self.rateVC = nil
                }
            }
        }
    }
    
    /// Gift选择器
    func showGiftVC(_ show: Bool = false, _ bookId: String = "", completion: @escaping (String) -> Void) {
        let h = TabBarMargin+ScreenW*0.7+76
        if giftVC == nil {
            giftVC = WNGiftVC()
            giftVC.baseId = bookId
            giftVC.view.frame = CGRect(x: 0, y: ScreenH, width: ScreenW, height: h)
            giftVC.sendClosure = { [weak self] str in
                self?.showGiftVC(completion: { _ in })
                completion(str)
            }
            addChild(giftVC)
            view.addSubview(giftVC.view)
            view.bringSubviewToFront(bgBtn)
            view.bringSubviewToFront(giftVC.view)
        }
        bgBtn.isHidden = !show
        UIView.animate(withDuration: 0.25, delay: 0, options: [.curveLinear, .allowUserInteraction], animations: {
            self.giftVC.view.transform = CGAffineTransform(translationX: 0, y: show ? -h : 0)
        }) { (finish) in
            if finish {
                if !show {
                    self.giftVC.view.removeFromSuperview()
                    self.giftVC.removeFromParent()
                    self.giftVC = nil
                }
            }
        }
    }
}
